package com.qfedu.web;

import com.qfedu.pojo.Account;
import com.qfedu.pojo.Cards;
import com.qfedu.pojo.History;
import com.qfedu.service.HistoryService;
import com.qfedu.service.PasswordService;
import com.qfedu.service.RechargeService;
import com.qfedu.service.WithdrawalService;
import com.qfedu.service.impl.HistoryServiceImpl;
import com.qfedu.service.impl.PasswordServiceImpl;
import com.qfedu.service.impl.RechargeServiceImpl;
import com.qfedu.service.impl.WithdrawalServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/centerServlet")
public class CenterServlet extends BaseServlet {
    private RechargeService rechargeService=new RechargeServiceImpl();
    private WithdrawalService withdrawalService=new WithdrawalServiceImpl();
    private PasswordService passwordService=new PasswordServiceImpl();
    private HistoryService historyService=new HistoryServiceImpl();


    protected void recharge(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String m = req.getParameter("money");
        BigDecimal m1 = new BigDecimal(m);//要转的钱
        Cards source = rechargeService.findCardsByCardNumber(req.getParameter("cardnumber"));
        Account target = rechargeService.findAccountByIdCode(req.getParameter("cardnumber"));
        if(source==null||target==null){
            req.setAttribute("msg", "卡号信息有误！！");
            req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
        }else {
            //转的钱大于0
            if (Double.parseDouble(m) <= 0 || source.getMoney().compareTo(m1) < 0) {
                req.setAttribute("msg", "金额有误！！");
                req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
            } else {
                //验证码
                String code = req.getParameter("code");
                String attribute = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
                if (!(attribute != null && attribute.equalsIgnoreCase(code))) {
                    req.setAttribute("msg", "验证码错误！！");
                    req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                    req.setAttribute("yu_e", source.getMoney());
                    req.setAttribute("money", req.getParameter("money"));
                    req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
                } else {

                    String paypassword = req.getParameter("password");
                    Account acc = passwordService.password(target.getIdcode(), paypassword);

                    /*支付密码判定*/
                    if (acc == null) {
                        // 跳回登录页面
                        req.setAttribute("msg", "支付密码错误");
                        req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                        req.setAttribute("yu_e", source.getMoney());
                        req.setAttribute("money", req.getParameter("money"));
                        req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
                    } else {
                        // 支付密码正确
                        BigDecimal m2 = source.getMoney();//source账户现有的钱
                        BigDecimal m3 = target.getMoney();//target账户现有的钱
                        BigDecimal money1 = m2.subtract(m1);
                        BigDecimal money2 = m3.add(m1);
                        int t = rechargeService.transfer(source, target, money1, money2);
                        if (t == 0) {
                            req.setAttribute("msg", "发生异常");
                            req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                            req.setAttribute("money", req.getParameter("money"));
                            req.setAttribute("yu_e", source.getMoney());
                            req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
                        } else {
                            String transferee = source.getCardnumber();
                            //.replaceAll("(\\d{4})\\d+(\\d{4})","$1****$2")
                            String outtransferee = "钱包";
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.ddHH:mm:ss");
                            String time = sdf.format(date);
                            historyService.addHistory(source.getIdcode(), transferee, outtransferee, m1, time, 0);
                            //充值status为0
                            resp.sendRedirect("/pages/transfer/recharge_success.jsp");//跳到成功页面
                        }
                    }
                }
            }
        }

    }

    protected void withdrawal(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String m = req.getParameter("money");
        BigDecimal m1 = new BigDecimal(m);
        Account source = withdrawalService.findAccountByIdCode(req.getParameter("cardnumber"));
        Cards target = withdrawalService.findCardsByCardNumber(req.getParameter("cardnumber"));
        if(source==null||target==null){
            req.setAttribute("msg", "卡号信息有误！！");
            req.getRequestDispatcher("/pages/transfer/whtidrawal.jsp").forward(req, resp);
        }else {
            BigDecimal m2 = source.getMoney();//source账户现有的钱
            BigDecimal m3 = target.getMoney();
            if (Double.parseDouble(m) <= 0) {
                req.setAttribute("msg", "提现金额有误！！");
                resp.sendRedirect("/pages/transfer/withdrawal.jsp");
                //余额小于提现金额
            }else if (m2.compareTo(m1) < 0) {
                req.setAttribute("msg", "余额不足！！");
                req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                req.getRequestDispatcher("/pages/transfer/withdrawal.jsp").forward(req, resp);
            } else {
                String code = req.getParameter("code");
                String attribute = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
                if (!(attribute != null && attribute.equalsIgnoreCase(code))) {
                    req.setAttribute("msg", "验证码错误！！");
                    req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                    req.setAttribute("money",req.getParameter("money"));
                    req.getRequestDispatcher("/pages/transfer/withdrawal.jsp").forward(req, resp);
                } else {
                    //日限额1W
                    int status = 1;
                    Date date1 = new Date();
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    String time1 = sdf1.format(date1);
                    BigDecimal sum = new BigDecimal(0);
                    BigDecimal b1 = new BigDecimal(10000);
                    List<History> history = historyService.findHistory(source.getIdcode(), status, time1);
                    if (history != null) {
                        for (History h : history) {
                            BigDecimal aaa = h.getMoney();
                            sum = sum.add(h.getMoney());
                        }
                    }
                    sum = sum.add(m1);
                    if (sum.compareTo(b1) > 0) {
                        req.setAttribute("msg", "本次提现将超日限额（1万），请重新输入金额");
                        req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                        req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
                    } else {
                        String paypassword = req.getParameter("password");
                        Account acc = passwordService.password(source.getIdcode(), paypassword);
                        /*支付密码判定*/
                        if (acc == null) {
                            // 跳回登录页面
                            req.setAttribute("msg", "支付密码错误");
                            req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                            req.setAttribute("money",req.getParameter("money"));
                            req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
                        } else {
                            BigDecimal money1 = m2.subtract(m1);
                            BigDecimal money2 = m3.add(m1);
                            int t = withdrawalService.transfer(source, target, money1, money2);
                            if (t == 0) {
                                req.setAttribute("msg", "发生异常");
                                req.setAttribute("cardnumber", req.getParameter("cardnumber"));
                                req.setAttribute("money",req.getParameter("money"));
                                req.getRequestDispatcher("/pages/transfer/withdrawal.jsp").forward(req, resp);
                            } else {
                                String transferee = "钱包";
                                String outtransferee = target.getCardnumber();
                                Date date = new Date();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.ddHH:mm:ss");
                                String time = sdf.format(date);
                                historyService.addHistory(source.getIdcode(), transferee, outtransferee, m1, time, 1);
                                //提现status为1
                                resp.sendRedirect("/pages/transfer/withdrawal_success.jsp");
                                //req.getRequestDispatcher("/pages/transfer/recharge_success.jsp").forward(req, resp);
                            }
                        }
                    }
                }
            }
        }
    }

    protected void findMoney(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        Cards source = rechargeService.findCardsByCardNumber(req.getParameter("cardnumber"));
        if(source==null){
            req.setAttribute("msg", "卡号信息有误！！");
            req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
        }
        req.setAttribute("yu_e",source.getMoney());
        req.setAttribute("cardnumber", req.getParameter("cardnumber"));
        req.getRequestDispatcher("/pages/transfer/recharge.jsp").forward(req, resp);
        }

}
